package com.tmc.service.intair;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.intair.EthFare;
import com.tmc.bean.intair.EthPricingReq;
import com.tmc.bean.intair.EthPricingResp;
import com.tmc.entity.intair.CommisionPolicy;
import com.tmc.service.cache.CacheServiceImpl;
import com.tmc.util.IntairUtil;
import com.tmc.util.ObjectUtil;
import com.tmc.vendor.intair.common.ServiceCenter;
import com.tmc.vendor.intair.common.VendorService;

@Service
public class EthPricingServiceImpl {

	@Autowired
	private CacheServiceImpl cache;

	private Log log = LogFactory.getLog(this.getClass());

	@Autowired
	private CommisionPolicyServiceImpl policyService;

	public CommonResult pricing(ContextInfo context, String fareKey) {
		if (ObjectUtil.noText(fareKey)) {
			return CommonResult.makeFail("fareKey不能为空！！");
		}
		CommonResult cacheResul = IntairUtil.getFareFromCache(fareKey, cache);
		if (!cacheResul.isSuccess()){
			return cacheResul;
		}
		EthFare fare = (EthFare)cacheResul.getObj();
		if (fare.getPrivateFareId() != null) {
			return CommonResult.makeSuccess("成功", fare);
		}
		VendorService service = ServiceCenter.getService(fare.getGds());
		try {
			EthPricingResp resp = service.pricing(context, new EthPricingReq(fare.getFlights()));
			if (resp == null) {
				return CommonResult.makeFail("验价失败，请重新查询！107");
			}
			EthFare result = ObjectUtil.makeTargetBean(fare, EthFare.class);
			result.setTicketPrice(resp.getTicketPrice());
			result.setTax(resp.getTotalPrice() - resp.getTicketPrice());
			result.setTotalAmount(resp.getTotalPrice());
			if (result.getCommisionPolicyId() != null) {
				CommisionPolicy policy = policyService.getById(context, result.getCommisionPolicyId());
				if (policy != null) {
					policyService.calculateCommision(fare, policy);
				}
			}
			return CommonResult.makeSuccess("成功", fare);
		} catch (Exception e) {
			log.error("pricing出错！", e);
			return CommonResult.makeFail("验价出错，请重新查询！106");
		}
	}
}
